interface ICarouselItem {
  id: number;
  name: string;
  detailId: number;
  sort: number;
  thumbnail: string;
  createTime: string;
}

interface IStoryItem {
  id: number;
  name: string;
  content: string;
  views: number;
  collects: number;
  thumbnail: string;
  createTime: string | null;
}

interface ISearchItem {
  name: String
}

interface IPageData {
  carouselList: ICarouselItem[];
  hotStories: IStoryItem[];
  searchQuery: string;
  searchResults: ISearchItem[];
  showSearchDropdown: boolean;
}

Page<IPageData>({
  data: {
    carouselList: [],
    hotStories: [],
    searchQuery: '',
    searchResults: [],
    showSearchDropdown: false
  },

  onLoad() {
    // 加载页面数据
    this.fetchCarouselList();
    this.fetchHotStories();
  },

  fetchCarouselList() {
    wx.request({
      url: 'https://fairy.ymdx.cn/v1/fairy/carouselList',
      method: 'POST',
      success: (res: any) => {
        if (res.data.code === 200) {
          this.setData({
            carouselList: res.data.data
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '获取轮播图失败',
          icon: 'error'
        });
      }
    });
  },

  navigateToStory(e: any) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/story/story?id=${id}`
    });
  },

  fetchHotStories() {
    wx.request({
      url: 'https://fairy.ymdx.cn/v1/fairy/findTop6Views',
      method: 'POST',
      success: (res: any) => {
        if (res.data.code === 200) {
          this.setData({
            hotStories: res.data.data
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '获取热门故事失败',
          icon: 'error'
        });
      }
    });
  },

  viewAllStories() {
    wx.navigateTo({
      url: '/pages/stories/stories'
    })
  },

  onShareAppMessage() {
    return {
      title: '童话大全 - 发现精彩的童话故事',
      path: '/pages/home/home'
    };
  },

  onSearchInput(e: any) {
    const query = e.detail.value;
    this.setData({ searchQuery: query });
    if (query.trim()) {
      this.searchStories(query);
    } else {
      this.setData({ 
        searchResults: [{name: '哈哈'}],
        showSearchDropdown: false
      });
    }
  },

  onSearchFocus() {
    if (this.data.searchQuery.trim() && this.data.searchResults.length > 0) {
      this.setData({ showSearchDropdown: true });
    }
  },

  searchStories(query: string) {
    wx.request({
      url: 'https://fairy.ymdx.cn/v1/fairy/search',
      method: 'POST',
      data: { name: query },
      success: (res: any) => {
        if (res.data.code === 200) {
          this.setData({
            searchResults: res.data.data,
            showSearchDropdown: true
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '搜索失败',
          icon: 'error'
        });
      }
    });
  }
});